import xss from "xss";
import localforage from "localforage";
// import { trim } from "./method/method";
// import router from "./router";
let url = "http://localhost:9999";
// import store from "../store/";
import axios from "axios";
// import qs from "qs";
Object.assign(axios.defaults, {
  // withCredentials: true,
  timeout: 10000,
});
function setHeader(config, uuid = "") {
  console.log(config.headers);
  if (config.method == "get") {
    Object.assign(config.headers, {
      ...config.headers,
      Authorization: uuid,
    });
  } else {
    Object.assign(config.headers, {
      ...config.headers,
      Authorization: uuid,
    });
    // config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    // // 将对象参数转换为序列化的 URL 形式（key=val&key=val）
    // config.data = qs.stringify(config.data);
  }

  // debugger
}
//xss校验
function checkXss(arr) {
  let result = true;
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    const item = arr[i];
    if (item != xss(item)) {
      result = false;
      break;
    }
  }
  return result;
}

const http = axios.create({
  baseURL: url,
});
// http request 拦截器
http.interceptors.request.use(
  async (config) => {
    let uuid = await localforage.getItem("token");
    setHeader(config, uuid);
    if (config.data) {
      let params = config.data;
      if (params) {
        let arr = Object.values(params);
        if (!checkXss(arr)) {
          //参数非法!
          return config;
        }
      }
    }
    return config;
  },
  (err) => {
    // debugger
    return Promise.reject(err);
  }
);

// http response 拦截器
http.interceptors.response.use(
  (res) => {
    // debugger
    return res;
  },
  (error) => {
    // debugger
    return error;
  }
);
export default http;
